/*
 * ===================================================================
 *  
 *      Filename:  log_client_color.c
 *
 *   Description:  This file is used to filter the msgs based on the regular
 *                 express which was sent through the udp port.We support a 
 *                 single regular express.
 *
 *       Version:  1.0
 *        Create:  2010/07/13
 *
 *        Author:  Keven Zhu     kevenzhu@tencent.com
 *     Copyright:  Reserved by Tencent.com Co.ltd
 *          
 * ====================================================================
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <regex.h>

#include "lib/util.h"
#include "log_client_api.h"

regex_t log_regex;

int global_color_status = COLOR_DISABLED;

int init_log_color()
{
    global_color_status = COLOR_DISABLED;
    return NOERR;
}

int finit_log_color()
{
    if(global_color_status == COLOR_ENABLED)
        regfree(&log_regex);
    global_color_status = COLOR_DISABLED;
    return NOERR;
}

int get_color_status()
{
    return global_color_status;
}

int set_color_status(int status,unsigned char* reg)
{
    int  iret  = 0;
    char *buff = (char*)reg;
    if(global_color_status == status)
    {
        log_doctor(doctor_level,"set the same operation on the color modules\n");
        return INVIO;
    }
    if( (status != ENABLE_COLOR_REQUEST) && (status != DISABLE_COLOR_REQUEST) )
        return INVIO;
    global_color_status = status;
    if(global_color_status == COLOR_ENABLED)
    {
        log_doctor(doctor_level,"enable color :%s\n",buff+2);
        buff = buff + 2;
        if ((iret = regcomp(&log_regex,buff, REG_EXTENDED|REG_NOSUB|REG_ICASE)) == 0)
        {
            return NOERR;
        }
        else
        {
            log_doctor(doctor_level,"error to compiler the regexp,disable the color function\n");
            regfree(&log_regex);
            global_color_status = COLOR_DISABLED;
            return INVIO;
        }
    }
    else
    {
        regfree(&log_regex);
    }
    return NOERR;
}

#define COLOR_RESULT 1
#define FILE_RESULT  0
int color_msg(char* msg)
{
    if (regexec(&log_regex, msg+3, 0, NULL, 0) == 0)
    {
        msg[2] = COLOR_RESULT;
    }
    else
    {
        msg[2] = FILE_RESULT;
    }
    return NOERR;
}
